﻿using Aliyun.OSS;
using Microsoft.AspNetCore.Http;

namespace QYmall.Core.Common.Helper
{
    /// <summary>
    /// 阿里云OSS帮助类
    /// </summary>
    public class OssHelper
    {
        /// <summary>
        /// 普通文件上传
        /// </summary>
        public static bool UploadFile(byte[] byteData, string? endpoint, string? accessKey, string? secretKey, string? bucketName, string? fileName)
        {
            var client = new OssClient(endpoint, accessKey, secretKey);
            using (Stream fileStream = new MemoryStream(byteData))
            {
                string md5 = Aliyun.OSS.Util.OssUtils.ComputeContentMd5(fileStream, byteData.Length);
                try
                {
                    //将文件md5值赋值给meat头信息，服务器验证文件MD5  
                    var objectMeta = new Aliyun.OSS.ObjectMetadata
                    {
                        ContentMd5 = md5,
                    };
                    //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5)
                    client.PutObject(bucketName, fileName, fileStream, objectMeta);
                    return true;
                }
                catch (Exception ex)
                {
                    throw new ResponseException(ex.Message, Emum.ErrorCode.Error, 500);
                }
            }
        }

        /// <summary>
        /// 大文件分片上传
        /// </summary>
        public static async Task<bool> UploadBigFileAsync(IFormFile file, int chunkSize, string? endpoint, string? accessKey, string? secretKey, string? bucketName, string? fileName)
        {
            // 初始化OOS对象
            var client = new OssClient(endpoint, accessKey, secretKey);
            // 初始化分片上传
            var initRequest = new InitiateMultipartUploadRequest(bucketName, fileName);
            var initResult = client.InitiateMultipartUpload(initRequest);
            var uploadId = initResult.UploadId;

            // 分片上传设置
            var partNumber = 1;
            var buffer = new byte[chunkSize]; // buffer size
            var partETags = new List<PartETag>();
            int bytesRead;
            // 开始分片上传
            try
            {
                using (var inputStream = file.OpenReadStream())
                {
                    while ((bytesRead = await inputStream.ReadAsync(buffer)) > 0)
                    {
                        using var partStream = new MemoryStream(buffer, 0, bytesRead);
                        var uploadPartRequest = new UploadPartRequest(bucketName, fileName, uploadId)
                        {
                            InputStream = partStream,
                            PartSize = bytesRead,
                            PartNumber = partNumber++
                        };
                        var partETag = client.UploadPart(uploadPartRequest).PartETag;
                        partETags.Add(partETag);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ResponseException(ex.Message, Emum.ErrorCode.Error, 500);
            }

            // 完成分片上传
            try
            {
                var completeRequest = new CompleteMultipartUploadRequest(bucketName, fileName, uploadId);
                foreach (var partETag in partETags)
                {
                    completeRequest.PartETags.Add(partETag);
                }
                var result = client.CompleteMultipartUpload(completeRequest);

                return true;
            }
            catch (Exception ex)
            {
                throw new ResponseException(ex.Message, Emum.ErrorCode.Error, 500);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        public static bool DeleteFile(string? endpoint, string? accessKey, string? secretKey, string? bucketName, string? fileName)
        {
            var client = new OssClient(endpoint, accessKey, secretKey);
            try
            {
                client.DeleteObject(bucketName, fileName);
                return true;
            }
            catch
            {
                return false;
            }
        }

    }
}
